﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using DevExpress.LookAndFeel;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;

namespace XCI.Windows
{
    [System.ComponentModel.Designer(typeof(GridStandardPagingDesigner))]
    public partial class GridControlStandardPaging : BaseUserControl
    {
        private PagingInfo _pagingInfo;
        private int _pageIndex;
        private bool _dataLoading;
        private bool _init;

        public GridControlStandardPaging()
        {
            InitializeComponent();
            if (DesignMode)
            {
                this.Dock = DockStyle.Bottom;
            }
        }

        /// <summary>
        /// 标准分页控件-默认每页大小
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static int DefaultPageSize { get; set; } = 100;

        /// <summary>
        /// 标准分页控件-分页大小下拉列表(多个之间逗号隔开)
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static string DefaultPageSizeList { get; set; } = "10,20,30,50,80,100,200,500";

        /// <summary>
        /// 标准分页控件-刷新按钮延迟时间(毫秒)
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static int DefaultRefreshDelay { get; set; } = 5000;

        /// <summary>
        /// 每页大小,0表示使用全局默认值
        /// </summary>
        [Category("XCI"), Description("每页大小"), DefaultValue(0)]
        public int PageSize { get; set; }

        /// <summary>
        /// 分页大小下拉列表,空表示使用全局默认值
        /// </summary>
        [Category("XCI"), Description("分页大小下拉列表"), DefaultValue(null)]
        public string PageSizeList { get; set; }

        /// <summary>
        /// 刷新按钮延迟时间,单位毫秒,0表示使用全局默认值
        /// </summary>
        [Category("XCI"), Description("刷新按钮延迟时间(毫秒)"), DefaultValue(0)]
        public int RefreshDelay { get; set; }

        /// <summary>
        /// 页数,从1开始
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int PageIndex => _pagingInfo?.PageIndex ?? 1;

        /// <summary>
        /// 总记录数
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int Total => _pagingInfo?.TotalCount ?? 0;

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public PagingInfo CurrentPagingInfo => _pagingInfo;

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public BasePageFilter CurrentPageFilter => new BasePageFilter(_pageIndex, PageSize);

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool DataLoading
        {
            get => _dataLoading;
            set
            {
                _dataLoading = value;
                // this.Enabled = !value;
                // barSummaryInfo.Text = "正在加载...";
            }
        }

        [Category("XCI"), Description("数据加载事件")]
        public event EventHandler<LoadStandardPagingDataEventArgs> LoadPagingData;

        [Category("XCI"), Description("自定义分页显示消息")]
        public event EventHandler<FormatPagingMessageEventArgs> FormatPagingMessage;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!WinFormHelper.IsDesignMode())
            {
                _init = true;
                if (PageSize == 0) PageSize = DefaultPageSize;
                if (RefreshDelay == 0) RefreshDelay = DefaultRefreshDelay;
                if (string.IsNullOrEmpty(PageSizeList)) PageSizeList = DefaultPageSizeList;

                editPageSize.EditValue = PageSize.ToString();

                //填充分页大小下拉列表
                FillPageSizeList(PageSizeList);

                editPageSize.Enabled = false;
                editGoPage.Enabled = false;
                editGoPage.Properties.MinValue = 1;
                editGoPage.Properties.MaxValue = 99999999;
                btnFirstPage.Enabled = false;
                btnLastPage.Enabled = false;
                btnPreviousPage.Enabled = false;
                btnNextPage.Enabled = false;
                btnRefresh.Enabled = false;
                labMessage.Text = " ";

                this.editPageSize.EditValueChanged += barPageSize_EditValueChanged;
                this.editGoPage.KeyPress += BarGoPage_KeyPress;

                this.btnFirstPage.Click += barFirstPage_ItemClick;
                this.btnPreviousPage.Click += barPreviousPage_ItemClick;
                this.btnNextPage.Click += barNextPage_ItemClick;
                this.btnLastPage.Click += barLastPage_ItemClick;
                this.btnRefresh.Click += barRefresh_ItemClick;
                _init = false;
            }
        }

        private void FillPageSizeList(string pageSizeList)
        {
            if (string.IsNullOrEmpty(pageSizeList)) return;
            this.editPageSize.Properties.Items.BeginUpdate();
            this.editPageSize.Properties.Items.Clear();
            var sz = pageSizeList.SplitToArray();
            foreach (var item in sz)
            {
                this.editPageSize.Properties.Items.Add(item);
            }
            this.editPageSize.Properties.Items.EndUpdate();
        }

        private void barPageSize_EditValueChanged(object sender, EventArgs e)
        {
            PageSize = editPageSize.EditValue.ToInt(20);
            LoadData(1);
        }

        private void BarGoPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == R.EnterKey)
            {
                LoadData(editGoPage.EditValue.ToInt());
                e.Handled = true;
            }
        }

        private void barRefresh_ItemClick(object sender, EventArgs e)
        {
            btnRefresh.Enabled = false;
            if (_pagingInfo != null)
            {
                LoadData(_pagingInfo.PageIndex);
            }
        }

        private void barFirstPage_ItemClick(object sender, EventArgs e)
        {
            LoadData(1);
        }

        private void barPreviousPage_ItemClick(object sender, EventArgs e)
        {
            if (_pagingInfo != null)
            {
                LoadData(_pagingInfo.PageIndex - 1);
            }
        }

        private void barNextPage_ItemClick(object sender, EventArgs e)
        {
            if (_pagingInfo != null)
            {
                LoadData(_pagingInfo.PageIndex + 1);
            }
        }

        private void barLastPage_ItemClick(object sender, EventArgs e)
        {
            if (_pagingInfo != null)
            {
                LoadData(_pagingInfo.TotalPages);
            }
        }

        public void LoadData(int pageIndex)
        {
            if (_init) return;
            if (LoadPagingData == null) throw new ArgumentException("请指定数据加载事件");
            if (_pagingInfo != null && pageIndex > _pagingInfo.TotalPages) pageIndex = _pagingInfo.TotalPages;
            if (pageIndex < 1) pageIndex = 1;
            this._pageIndex = pageIndex;

            LoadPagingData.Invoke(this, new LoadStandardPagingDataEventArgs { PageFilter = CurrentPageFilter });
        }

        public void BindingInfo(PagingInfo info)
        {
            _pagingInfo = info;
            editGoPage.Properties.MaxValue = info.TotalPages;
            editGoPage.EditValue = _pagingInfo.PageIndex;

            editPageSize.Enabled = _pagingInfo.HasData;
            editGoPage.Enabled = _pagingInfo.HasData;

            btnFirstPage.Enabled = _pagingInfo.HasData && !_pagingInfo.IsFirst;
            btnLastPage.Enabled = _pagingInfo.HasData && !_pagingInfo.IsLast;
            btnPreviousPage.Enabled = _pagingInfo.HasData && _pagingInfo.HasPreviousPage;
            btnNextPage.Enabled = _pagingInfo.HasData && _pagingInfo.HasNextPage;

            btnRefresh.Enabled = false;
            TimerHelper.DelayRun(RefreshDelay, () =>
            {
                btnRefresh.Enabled = _pagingInfo.HasData;
            });

            if (FormatPagingMessage == null)
            {
                labMessage.Text = GetDefaultPagingMessage(_pagingInfo);
            }
            else
            {
                var args = new FormatPagingMessageEventArgs { PagingInfo = _pagingInfo };
                FormatPagingMessage.Invoke(this, args);
                labMessage.Text = string.IsNullOrEmpty(args.PagingMessage) ? GetDefaultPagingMessage(_pagingInfo) : args.PagingMessage;
            }
        }

        public string GetDefaultPagingMessage(PagingInfo info)
        {
            return $"显示{info.RecordStartIndex}到{info.RecordEndIndex},共{info.TotalPages}页{info.TotalCount}条记录";
        }

        //private void layoutControl1_Paint(object sender, PaintEventArgs e)
        //{
        //    if (DesignMode) return;
        //    var isDarkSkin = DevExpress.Utils.Frames.FrameHelper.IsDarkSkin(UserLookAndFeel.Default);
        //    if (pen == null) pen = isDarkSkin ? new Pen(Color.FromArgb(75, 75, 75)) : new Pen(Color.FromArgb(200, 200, 200));
        //    e.Graphics.DrawLine(pen, 0, 0, Width, 0);
        //}
    }

    public class GridStandardPagingDesigner : System.Windows.Forms.Design.ControlDesigner
    {
        /// <summary>
        /// 不允许调整控件的高度
        /// </summary>
        public override SelectionRules SelectionRules => SelectionRules.Visible | SelectionRules.Moveable;
    }


    public class LoadStandardPagingDataEventArgs : EventArgs
    {
        /// <summary>
        /// 分页请求信息
        /// </summary>
        public BasePageFilter PageFilter { get; set; }
    }
}
